package com.cw.util;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Digit {
	public static String appendzero(int base) {
		if (base < 10) {
			return "0" + base;
		}
		return String.valueOf(base);
	}

	// com
	public static int bj(int a, int b) {
		return a > b ? 1 : (a == b ? 0 : -1);
	}

	private static int comp(int p, int n) {
		if (n == 0) {
			return 1;
		} else {
			return p * comp(p, n - 1);
		}
	}

	public static int[] getNRandom(int m, int k) {
		int[] input = new int[m];
		for (int i = 0; i < m; i++) {
			input[i] = i + 1;
		}
		return getNRandom(input, k);
	}

	public static int[] getNRandom(int[] input) {
		return getNRandom(input, input.length);
	}

	public static int[] getNRandom(int[] input, int k) {
		Random r = new Random();
		int[] output = new int[k];
		if (input.length <= 0 || input.length < k) {
			return null;
		}
		for (int i = 0; i < output.length; i++) {
			int temp = 0;
			int rad = r.nextInt(input.length - i);
			output[i] = input[rad];
			temp = output[i];
			input[rad] = input[input.length - i - 1];
			input[input.length - i - 1] = temp;
		}
		return output;
	}

	// judge a number prime
	public static boolean prime(int n) {
		if (n <= 1) {
			return false;
		}
		if (n == 2 || n == 3) {
			return true;
		}
		for (int k = 2; k <= Math.sqrt(n); k++) {

			if (n % k == 0) {
				return false;
			}
		}
		return true;
	}

	// num revert to bin
	public static char[] revert(int n) {
		char[] bin = new char[10];
		for (int i = 10; i > 0; i--) {
			if (n >= comp(2, i - 1)) {
				bin[10 - i] = '1';
				n = n - comp(2, i - 1);
			} else {
				bin[10 - i] = '0';
			}
		}
		return bin;
	}

	public Digit() {
	}

	/**
	 * judge digit is odd?
	 * 
	 * @param digit
	 *            int
	 * @return boolean
	 */
	public boolean odd(int digit) {
		if (digit % 2 == 1) {
			return true;
		}
		return false;
	}

	/**
	 * find how many oddnum in the digit
	 * 
	 * @param digit
	 *            int[]
	 * @return int
	 */
	public int oddnum(int[] digit) {
		int num = 0;
		for (int i = 0; i < digit.length; i++) {
			if (odd(digit[i])) {
				num++;
			}
		}
		return num;
	}
	/**
	 * judge 'str' is num or string
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str)
	{
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	} 
}
